package com.Smart.smartscals.Activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.Smart.smartscals.DataBase.DataBaseService;
import com.Smart.smartscals.DataBase.DownLoadDataUtils;
import com.Smart.smartscals.DataBase.FileHelpService;
import com.Smart.smartscals.DataBase.SharedParam;
import com.Smart.smartscals.DataBase.TimeDateUtils;
import com.Smart.smartscals.Entity.DownLoadDataEntity;
import com.Smart.smartscals.Entity.SaveBodyInfoEntity;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ActivityCloud extends Activity {
	private ListView import_listview;
	private ImageButton importbtn;
	private ImageButton backbtn;

	private List<String> items = null;
	private String basepath = "data/data/com.example.databasedemo";
	private File file;

	private SharedParam sp;
	private DataBaseService mDataService;
	private FileHelpService mFileHelpService;

	private String curUserName;
	private ListView export_listview;
	// private Button export_sdcardbtn;
	// private Button export_mailbtn;
	private int curChecked;
	private Button upLoad_btn;
	private Button downLoad_btn;
	private long exFromDate;
	private long exToDate;
	private TimeDateUtils timeDatautils;
	private DownLoadDataUtils downLoadUtils;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_updata1);

		sp = SharedParam.getInstance(this);
		mDataService = DataBaseService.getInstance(this);
		mFileHelpService = new FileHelpService(this);
		downLoadUtils = new DownLoadDataUtils(ActivityCloud.this);
		curUserName = sp.getActiveUserName();

		export_listview = (ListView) findViewById(R.id.export_listview);
		downLoad_btn = (Button) findViewById(R.id.downLoad_data);
		upLoad_btn = (Button) findViewById(R.id.upLoad_Data);
		backbtn = (ImageButton) findViewById(R.id.ex_back_btn);

		String[] listcycle = this.getResources().getStringArray(
				R.array.exdata_type);
		ArrayAdapter<String> madapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_single_choice, listcycle);
		export_listview.setAdapter(madapter);

		export_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				curChecked = arg2;
			}
		});

		backbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		// 下载数据
		downLoad_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 先去数据库查找最后一次上传时间

				String lastDownLoadTime = downLoadUtils
						.getLastloadTime(curUserName);
				if (lastDownLoadTime == null) {
					lastDownLoadTime = "1970-01-01 12:00:00";
				}
				// 1. 调用ehealth_getAllBodyCompositionData这个函数的接口进行数据的下载
				// 接口的地址
				final String url = "http://218.24.163.216/eblter/Service1.asmx/ehealth_downData";
				final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

				// set上传人体数据到t_BodyCompsitionData表中

				// ~~~~~~~~注意!! 此处要传入登陆或者是注册的时候返回的authkey;
				// ~~~~~~~~注意!! 此处要传入登陆或者是注册的时候返回的authkey;
				// ~~~~~~~~注意!! 此处要传入登陆或者是注册的时候返回的authkey;
				nameValuePairs
						.add(new BasicNameValuePair("authkey", "LOWCJTK9"));
				// 5代表的是5：t_BodyCompositionData人体成分表
				nameValuePairs.add(new BasicNameValuePair("datatable", "5"));
				nameValuePairs.add(new BasicNameValuePair("lastdown_datetime",
						lastDownLoadTime));
				Log.i("blackk22", "lastDownLoadTime-->" + lastDownLoadTime);

				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

						HttpPost httppost = new HttpPost(url);
						try {
							httppost.setEntity(new UrlEncodedFormEntity(
									nameValuePairs, HTTP.UTF_8));
							HttpClient _httpclient = new DefaultHttpClient();
							HttpResponse response = _httpclient
									.execute(httppost);

							Log.i("blackk22", "resCode_DownLoad = "
									+ response.getStatusLine().getStatusCode()); // 获取响应码
							// Log.i("blackk22", "result_DownLoad = " +
							// EntityUtils.toString(response.getEntity(),
							// "utf-8"));//获取服务器响应内容

							int resCode = response.getStatusLine()
									.getStatusCode();
							timeDatautils = new TimeDateUtils();
							long currTimes = System.currentTimeMillis();
							if (resCode == 200) {
								// 下载成功，保存下载的时间到本地数据库
								String currtimesStr = timeDatautils
										.convert2FileDate(currTimes);
								downLoadUtils.insertloadTimeInfo(curUserName,
										currtimesStr);
								Log.i("blackk22", "上传的时间已经保存");

								String jsonStr = EntityUtils.toString(
										response.getEntity(), "utf-8")
										+ "";
								// 解析数据，返回一个DownloadDataEntity的集合
								List<DownLoadDataEntity> list = downLoadUtils
										.parserDownloadData(jsonStr);
								Log.i("blackk22", list.size() + "");
								for (int i = 0; i < list.size(); i++) {
									DownLoadDataEntity downLoadEntity = list
											.get(i);
									// 先通过这个时间去数据库中查找，
									SaveBodyInfoEntity bodyInfoEntity = new SaveBodyInfoEntity();
									String downLoadTime = downLoadEntity
											.getData();

									long date = timeDatautils
											.strTime2LongTime(downLoadTime);
									bodyInfoEntity.setDate(date);
									bodyInfoEntity.setUserName(curUserName);
									bodyInfoEntity.setBodyFat(Float
											.parseFloat(downLoadEntity.getFat()));
									bodyInfoEntity.setWeight(Float
											.parseFloat(downLoadEntity
													.getWeight()));
									String loadTime = downLoadTime.substring(0,
											10);
									long loadtimeLong = timeDatautils
											.strTimeCovLongTime(loadTime);
									downLoadUtils.insertLoadDownData(
											bodyInfoEntity, loadtimeLong);

									Log.i("blackk22", downLoadTime);

									// 如果数据库中有数据就不插入,如果没有就插入数据

								}
							}

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}).start();

				// 并且把当前时间存在数据库的，下载时间表中
				// 2. 数据要求：先去本地数据库查找对应天有没有数据，是当天的那么不去更新
				// 3. 如果不是当天的时间则去查询从最后一天数据的时间到当前日期的数据
				// 4. 解析xml，把数据都解析出来。放到一个Entity实体中去
				// 5. 将查询到的数据插入到插入数据库

			}
		});

		// 上传数据
		upLoad_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				try {
					boolean isexport2SD = exportData2SDcard();
					file = new File(mFileHelpService.getAbsoluteExPath());
					if (isexport2SD) {
						System.out.println(isexport2SD);
						// 使用xUrils将件上传到服务器 或者是其他的方法
						FileInputStream in = null;
						in = new FileInputStream(file.getAbsolutePath());// 文件的位置
						long totalAudioLen = in.getChannel().size();
						byte[] data = new byte[(int) totalAudioLen];
						in.read(data);
						// 上传文件的名字
						String fileNameStr = curUserName.replace(" ", "") + "-"
								+ TimeDateUtils.convert2FileName(exFromDate)
								+ "-"
								+ TimeDateUtils.convert2FileName(exToDate)
								+ ".txt";
						// String fileNameStr =
						// FileHelpService.BASEPATH+"/test.txt";
						String uploadBuffer = Base64.encodeToString(data,
								Base64.DEFAULT); // 进行Base64编码
						in.close();
						// 接口的地址
						final String url = "http://218.24.163.216/eblter/Service1.asmx/ehealth_bigdataupload";
						final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

						// set上传人体数据到t_BodyCompsitionData表中
						nameValuePairs.add(new BasicNameValuePair("tablename",
								"t_BodyCompositionData"));
						// set文件名称
						nameValuePairs.add(new BasicNameValuePair("fileName",
								fileNameStr));
						// set用base64编码后的文件
						nameValuePairs.add(new BasicNameValuePair("fileBt",
								uploadBuffer));
						nameValuePairs.add(new BasicNameValuePair("isCreate",
								"true"));
						nameValuePairs.add(new BasicNameValuePair("isClose",
								"true"));

						new Thread(new Runnable() {
							@Override
							public void run() {
								System.out.println("线程已启动：");
								// TODO Auto-generated method stub
								HttpPost httppost = new HttpPost(url);
								try {
									httppost.setEntity(new UrlEncodedFormEntity(
											nameValuePairs, HTTP.UTF_8));
									HttpClient _httpclient = new DefaultHttpClient();
									HttpResponse response = _httpclient
											.execute(httppost);

									Log.i("blackk22", "resCode = "
											+ response.getStatusLine()
													.getStatusCode()); // 获取响应码

									Log.i("blackk22",
											"result = "
													+ EntityUtils.toString(
															response.getEntity(),
															"utf-8"));// 获取服务器响应内容

								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).start();

					} else {
						// 生成文件失败
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

	}

	public boolean exportData2SDcard() {
		boolean isexportData = false;
		if (curChecked != 5) {
			Calendar cal = Calendar.getInstance();
			exFromDate = TimeDateUtils.getRangeFromDate(curChecked);
			exToDate = TimeDateUtils.setToDate(cal);
			Log.e("wutl", "fromDate/toDate:" + exFromDate + "/" + exToDate);
			if (mFileHelpService.writeFileData(curUserName, exFromDate,
					exToDate, mDataService, this)) {
				isexportData = true;
			} else {
				isexportData = false;
			}
		} else {
			if (mFileHelpService.writeFileData(curUserName, 0,
					System.currentTimeMillis(), mDataService, this)) {
				isexportData = true;
			} else {
				isexportData = false;
			}
		}
		return isexportData;
	}
}
